package org.sean.framework.feign;

import feign.Response;
import feign.codec.Decoder;
import org.sean.framework.bean.BaseResult;
import org.sean.framework.code.StatusInfo;
import org.sean.framework.exception.StatusException;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * 解码器  响应不使用BaseResult包装时,可删除
 */
public class ClientEntityDecoder extends ResponseEntityDecoder {

    public ClientEntityDecoder(Decoder decoder) {
        super(decoder);
    }

    @Override
    public Object decode(Response response, Type type) throws IOException {
        if (!type.getTypeName().startsWith(BaseResult.class.getName())) {
            throw new StatusException(StatusInfo.notSupported().setAnyMessage("Client 定义错误,返回值不是BaseResult"));
        }
        Object result = super.decode(response, type);
        if (result instanceof BaseResult && !((BaseResult<?>) result).isSuccess()) {
            throw new StatusException((BaseResult<?>) result);
        }
        return result;
    }
}
